<template>
  <div>
    <Header :title="'返回'" :subTitle="''" :hasBackPath="true" @headerBack="headerBack"></Header>
    <a-spin :spinning="spinning" size="large">
      <a-card :bordered="false">
        <a-form-model ref="rulesForm" :model="form" :rules="rules" :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }" :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }">
          <a-form-model-item label="主题搭配名称" prop="matchName">
            <a-input v-model="form.matchName" placeholder="请输入" :max-length="20" />
          </a-form-model-item>
          <a-form-model-item label="推荐理由" prop="recommReason">
            <a-textarea v-model="form.recommReason" placeholder="请输入,不超过100个字" :max-length="100" :auto-size="{ minRows: 3, maxRows: 5 }" />
          </a-form-model-item>
          <a-form-model-item label="所属活动品牌" prop="joinBrandId">
            <a-select v-model="form.joinBrandId" @change="handleChange">
              <a-select-option :value="item.value" v-for="item in brands" :key="item.value">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="关联LOOK" required>
            <a-button style="margin-left: 18px" type="primary" icon="plus" @click="showLook">添加</a-button>
          </a-form-model-item>
          <a-form-model-item label="搭配包含单品" required>
            <a-table :dataSource="productList" :columns="columns" :rowKey="(record, index) => index" :pagination="false">
              <span slot="serial" slot-scope="text, record, index">
                {{ index + 1 }}
              </span>
              <span slot="product" slot-scope="text, record" class="goods">
                <img :src="record.productImage" alt="" class="thumbnail" @click="showGoodInfo(record)" />
                <span class="goods-info">
                  <h3>{{ record.productBrand }} {{ record.productName }}</h3>
                  <span class="code">{{ record.productColor }}/{{ record.productColorName }}</span>
                </span>
              </span>
            </a-table>
          </a-form-model-item>
          <a-form-model-item label="搭配图片" prop="matchingPicture" required>
            <JImageUpload :uploadParams="getUploadParams()" :fileSize="5" :isMultiple="true" :number="9" :accept="'image/*'" @fileChange="fileImageChange" v-model="imgList"></JImageUpload>
            <div class="upload__tip" style="line-height: 16px;">3:4图片比例，支持jpg/png/gif格式，文件大小不超过5M，最多9张</div>
          </a-form-model-item>
          <a-form-model-item label="营销标识" prop="marketingStatus" required>
            <a-radio-group v-model="form.marketingStatus" name="radioGroup">
              <a-radio :value="0">无</a-radio>
              <a-radio :value="1">NEW</a-radio>
              <a-radio :value="2">HOT</a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="排序值" prop="sortNo">
            <a-input-number v-model="form.sortNo" placeholder="请输入" :max="999" :min="1" style="width:150px" /><br />排序值仅支持输入数字，数字越小越靠前。排序值相同，创建时间越近越靠前
          </a-form-model-item>
          <a-form-model-item label="状态" prop="status" required>
            <a-radio-group v-model="form.status" name="radioGroup">
              <a-radio :value="0">上架</a-radio>
              <a-radio :value="1">下架</a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item :wrapperCol="{ span: 24 }" style="text-align: center">
            <a-button type="primary" @click="save">保存</a-button>
            <a-button style="margin-left: 8px" @click="headerBack">取消</a-button>
          </a-form-model-item>
        </a-form-model>
      </a-card>
    </a-spin>
    <LookModal ref="lookModal" @addLook="getMatch"></LookModal>
    <!-- 商详 -->
    <GoodInfoModal ref="goodInfoModal"></GoodInfoModal>
  </div>
</template>
<script>
import Header from '@/views/box/components/layouts/Header'
import JImageUpload from '@/components/qiniuUpload/JImageUpload.vue'
import LookModal from '@/views/box/components/boxLookModal'
import GoodInfoModal from '../../components/GoodInfoModal'
import { themeMixin } from './util/mixin'
import { getThemeMatchById, addThemeMatch, editThemeMatchById } from '@/api/box/theme'
import { addCondition } from '@api/box/boxLook'
const columns = [
  {
    title: '序号',
    align: 'center',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '商品',
    align: 'center',
    scopedSlots: { customRender: 'product' }
  },
  {
    title: '款号',
    dataIndex: 'productCode',
    align: 'center'
  }
]
export default {
  mixins: [themeMixin],
  components: { Header, JImageUpload, LookModal, GoodInfoModal },
  data() {
    this.columns = columns
    return {
      spinning: false,
      activityId: '',
      activityName: '',
      lookId: '',
      form: {
        matchingPicture: [],
        status: 0,
        marketingStatus: 0
      },
      rules: {
        matchName: [{ required: true, message: '请输入名称，最多20个字', trigger: 'blur', max: 20 }],
        recommReason: [{ required: true, message: '请输入文案，最多100个字', trigger: 'blur', max: 100 }],
        joinBrandId: [{ required: true, message: '请选择品牌', trigger: ['blur', 'change'] }],
        matchingPicture: [{ required: true, message: '请上传搭配图片', trigger: ['blur', 'change'] }],
        sortNo: [{ required: true, message: '请输入排序值，最大999', trigger: 'blur' }]
      },
      imgList: [],
      brands: [],
      productList: []
    }
  },
  beforeRouteLeave(to, from, next) {
    this.$destroy()
    next()
  },
  activated() {
    this.initialPage()
  },
  methods: {
    // 初始化页面
    async initialPage() {
      this.activityId = this.$route.params.themeId
      this.lookId = this.$route.params.id
      await this.fetchActivityDetail()
      if (this.lookId != 'add') {
        await this.fetchLookDetail()
        let res = await this.fetchMatchDetail(this.form.lookId)
        if (res.code == 0) {
          this.productList = res.data.productList
        } else {
          this.$message.warning(res.msg)
        }
      }
      this.spinning = false
    },
    // 活动详情
    async fetchActivityDetail() {
      this.spinning = true
      let res = await this.fetchThemeActivityById(this.activityId)
      if (res.code == 0) {
        let joinBrandId = res.data.bthemeActivity.joinBrandId.split(',')
        this.brands = this.brandsList.filter(e => joinBrandId.includes(e.value))
        this.activityName = res.data.bthemeActivity.activityName
      } else {
        this.$message.warning(res.msg)
      }
    },
    // 查询搭配详情
    fetchLookDetail() {
      let params = {
        requestData: {
          id: this.lookId
        }
      }
      return getThemeMatchById(params).then(res => {
        if (res.code == 0) {
          this.form = res.data
          // this.form.activityName = this.activityName
          // this.form.activityId = this.activityId
          this.imgList = res.data.matchingPicture ? res.data.matchingPicture.split(',') : []
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    fileImageChange(list) {
      console.log('list', list)
      this.form.matchingPicture = list.length > 0 ? list : undefined
    },
    handleChange(value) {
      console.log(`selected ${value}`)
      this.form.joinBrandId = value
    },
    // 添加look
    showLook() {
      this.$refs.lookModal.show()
    },
    // 获取选择的Look详情
    async getMatch(record) {
      console.log(record)
      let res = await this.fetchMatchDetail(record.id)
      if (res.code == 0) {
        this.form.lookId = record.id
        const { fashionerMatch, productList, galleryList } = res.data
        const { extendJson } = fashionerMatch
        console.log(extendJson, productList)
        const imgList = galleryList.filter(e => e.type == 0).length > 0 ? galleryList.filter(e => e.type == 0).map(item => item.url) : []
        console.log(imgList)
        this.form.matchingPicture = imgList
        this.imgList = imgList
        this.productList = productList
      } else {
        this.$message.warning(res.msg)
      }
    },
    fetchMatchDetail(id) {
      let params = {
        id: id
      }
      return addCondition(params).then(res => {
        return res
      })
    },
    showGoodInfo(record) {
      this.$refs.goodInfoModal.show(record.productId, record.skuId)
    },
    // 保存
    save() {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          let matchingPicture = this.form.matchingPicture.map(e => e.url).join(',')
          this.form.matchingPicture = matchingPicture
          this.form.joinBrandName = this.brands.filter(e => e.value == this.form.joinBrandId)[0].name
          console.log(this.form)
          let formValue = {
            activityId: this.activityId,
            activityName: this.activityName,
            ...this.form
          }
          console.log(formValue)
          if (this.lookId == 'add') {
            this.addLook(formValue)
          } else {
            this.editLook(formValue)
          }
        }
      })
    },
    addLook(formValue) {
      let params = {
        requestData: formValue
      }
      addThemeMatch(params).then(res => {
        if (res.code == 0) {
          this.$message.success('保存成功！')
          this.$router.back()
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    editLook(formValue) {
      let params = {
        requestData: { id: this.lookId, ...formValue }
      }
      editThemeMatchById(params).then(res => {
        if (res.code == 0) {
          this.$message.success('保存成功！')
          this.$router.back()
        } else {
          this.$message.warning(res.msg)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.goods {
  display: flex;
  .thumbnail {
    height: 100px;
    margin-right: 12px;
    // border: 1px dashed #cdcdcd;
    width: 100px;
    object-fit: scale-down;
    // background: #fff;
    cursor: pointer;
  }
  .goods-info {
    text-align: left;

    h3 {
      font-size: 16px;
      margin-top: 10px;
    }
    .code {
      font-size: 12px;
      display: block;
    }
  }
}
</style>

